package com.lxyk.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.lxyk.yygh.oss.service.FileService;
import com.lxyk.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    //上传图片
    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        // 强烈建议不要把访问凭证保存到工程代码里，否则可能导致访问凭证泄露，威胁您账号下所有资源的安全。本代码示例以从环境变量中获取访问凭证为例。运行本代码示例之前，请先配置环境变量。
        //EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        String accessKeyId=ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String secret=ConstantOssPropertiesUtils.SECRECT;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantOssPropertiesUtils.BUCKET;

        OSS ossClient =null;
        try {

            //创建ossClient实例
            ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,secret);

            // 保存的路径。fileName
            //年月日+uuid+filename.jpg
            String fileName=file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String timeUrl = new DateTime().toString("yyyy-mm-dd");
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            fileName=timeUrl+"/"+uuid+fileName;
            // 创建PutObjectRequest对象。
            InputStream fileInputStream = file.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, fileInputStream);
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //返回文件名称
            //上传之后文件路径
            // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return null;
    }
}
